const Koa = require('koa');
const Router = require('koa-router')
const app = new Koa()
const router = new Router()
// 挂载中间件
// ctx => {request请求头 response响应头} context
// request请求头 response响应头
// app.use(async (ctx,next) => {
//     // ctx.response.body = 'hello world'
//     await next()
// })
// router.get('/home', async (ctx) => {
//     ctx.body = 'home'
// })
// router.get('/list', async (ctx) => {
//     ctx.body = [1,2,3]
// })
// 挂载路由中间件
// app.use(router.routes())
// 洋葱圈模型
// 1. 洋葱圈运行机制  2. ctx上下文是互通的 可以向后传递
app.use(async (ctx,next) => {
    const startTime = Date.now();
    console.log(1,ctx.id)
    await next()
    const endTime = Date.now()
    console.log(2,ctx.id)
    ctx.body = ctx.id;
})

app.use(async (ctx,next) => {
    console.log(3,ctx.id)
    await new Promise((res) => {
        setTimeout(() => {
            ctx.id = 1000
            res()
        },800)
    })
    await next()
    console.log(4,ctx.id)
})
app.use(async (ctx,next) => {
    console.log(5, ctx.id)
})

app.listen(8888,() => {
    console.log('listen to 8888')
})
